package com.demo.sonar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class SonarQubeApiClient {

//    private static final String SONAR_URL = "http://10.252.171.40:30003/api/projects/index?projectKeys=com.grg.itp:account-mgr";
    private static final String SONAR_URL = "http://10.252.171.40:9000/api/projects/index?projectKeys=AYDfecQJwrnmy-TFCJuB";
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "123456";

    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = createAuthenticatedClient()) {
            HttpGet request = new HttpGet(SONAR_URL);
            HttpResponse response = httpClient.execute(request);

            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String jsonResponse = EntityUtils.toString(entity, "UTF-8");

            System.out.println("Status Code: " + statusCode);
            System.out.println("Response: " + jsonResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static CloseableHttpClient createAuthenticatedClient() {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
        provider.setCredentials(AuthScope.ANY, credentials);
        return HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    }
}